/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * BuscaCliente.java
 *
 * Created on 10/02/2012, 02:00:29 PM
 */

package sst.Vistas;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author alberto
 */
public class BuscaCliente extends javax.swing.JDialog {
 //tabla modelo:
    public static DefaultTableModel modelo = new DefaultTableModel();
    //filas
    Object[] filas;
    /** Creates new form jdSQL */
    /** Creates new form BuscaCliente */


    public class seleccion {

public seleccion(){

}
public int select(String sColName, JTable ta)
{
int nColumns = 0, nLen = 0, indX = 0;
nLen = ta.getColumnCount();
for (int i = 0; i < nLen; i++){
if (sColName.equals(ta.getColumnName(i)) )
{
indX = i;
}
}

return indX;
}
    }

    public BuscaCliente(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        
        this.setDefaultCloseOperation(this.DISPOSE_ON_CLOSE);
        botonBuscar.doClick();

        //this.setSize(this.getToolkit().getScreenSize());
        setLocationRelativeTo(null);
        
    }

    public BuscaCliente(){
    initComponents();
    setLocationRelativeTo(null);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        botonBuscar = new javax.swing.JButton();
        textRif = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        jtResultado = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Busqueda de Clientes");
        setModal(true);

        botonBuscar.setText("Buscar");
        botonBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botonBuscarActionPerformed(evt);
            }
        });

        textRif.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                textRifKeyPressed(evt);
            }
        });

        jtResultado.setAutoCreateRowSorter(true);
        jtResultado.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jtResultado.getTableHeader().setReorderingAllowed(false);
        jtResultado.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jtResultadoMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jtResultado);

        jLabel1.setFont(new java.awt.Font("DejaVu Sans", 1, 16));
        jLabel1.setText("RIF:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(118, 118, 118)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(textRif, javax.swing.GroupLayout.DEFAULT_SIZE, 434, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(botonBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(259, 259, 259))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 954, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(25, 25, 25)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(botonBuscar)
                    .addComponent(textRif, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 401, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    

    private void botonBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonBuscarActionPerformed
         try{
           // Conectar a mysql:
             Class.forName("com.mysql.jdbc.Driver");
             Connection conne=(Connection) DriverManager.getConnection("jdbc:mysql://localhost/sst","root","alberto.1990");
           // creo la consulta sql:
             Statement consulta=(Statement) conne.createStatement();                         //textField de busqueda
             ResultSet rs = consulta.executeQuery("select * from cliente where rif like'%"+textRif.getText()+"%'");
            // reasigno un modelo en blanco:
                 modelo = new DefaultTableModel();
                 jtResultado.setModel(modelo);


            //creamos la columnas de nuestra tabla:
                 modelo.addColumn("rif");
                 modelo.addColumn("nombreCliente");
                 modelo.addColumn("telfono");
                 modelo.addColumn("direccion");
                 modelo.addColumn("correo");

            //asigno el tamaño del arreglo co la cantidad de columnas:
                 filas = new Object[modelo.getColumnCount()];
            //escribo las filas:
            while (rs.next())
            {                   //cantidad de columnas
                 for (int i=0;i<modelo.getColumnCount();i++){
                  filas[i] = rs.getObject(i+1);
                 }
                 //escribo las filas del resultado SQL//
                 modelo.addRow(filas);
                 jtResultado.setModel(modelo);
                 

            }
              //error de lectura a los campos de la bd
              } catch(SQLException e){
            JOptionPane.showMessageDialog(null,"Error sql no se pueden leer datos");
          //error desconocido //por lo general no hay conexion con la base de datos
        } catch(ClassNotFoundException e){
            JOptionPane.showMessageDialog(null,"Error al leer la base de datos");

        }
    }//GEN-LAST:event_botonBuscarActionPerformed

    private void textRifKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_textRifKeyPressed
         if(evt.getKeyCode() == evt.VK_ENTER) {
        botonBuscar.doClick();
        }
         if(evt.getKeyCode() == evt.VK_ESCAPE){
         this.dispose();
         }


    }//GEN-LAST:event_textRifKeyPressed

    private void jtResultadoMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jtResultadoMouseClicked

            Principal a = new Principal();
            seleccion sel = new seleccion();
            
            int indx = sel.select("rif", jtResultado);
            int indx2 = sel.select("nombreCliente", jtResultado);
            int indx3 = sel.select("telfono", jtResultado);
            int indx4 = sel.select("direccion", jtResultado);
            int indx5 = sel.select("correo", jtResultado);

            String rif = (String) jtResultado.getValueAt(jtResultado.getSelectedRow(),indx);
            //clien.textRif.setText(rif);
             String nombre = (String) jtResultado.getValueAt(jtResultado.getSelectedRow(),indx2);
             String telefono = (String) jtResultado.getValueAt(jtResultado.getSelectedRow(),indx3);
             String direccion = (String) jtResultado.getValueAt(jtResultado.getSelectedRow(),indx4);
             String correo = (String) jtResultado.getValueAt(jtResultado.getSelectedRow(),indx5);
             
            this.dispose();
             RegistroCliente clien = new RegistroCliente(a, true, rif, nombre,telefono,direccion,correo);
            

             clien.setVisible(true);
               
             
             
           /* clien.textRif.setText(jtResultado.getValueAt(jtResultado.getSelectedRow(), indx).toString());
            clien.textNombre.setText(jtResultado.getValueAt(jtResultado.getSelectedRow(), indx2).toString());
            clien.textTelefono.setText(jtResultado.getValueAt(jtResultado.getSelectedRow(), indx3).toString());
            clien.textDireccion.setText(jtResultado.getValueAt(jtResultado.getSelectedRow(), indx4).toString());
            clien.textCorreo.setText(jtResultado.getValueAt(jtResultado.getSelectedRow(), indx5).toString());
      */  
    }//GEN-LAST:event_jtResultadoMouseClicked

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                BuscaCliente dialog = new BuscaCliente(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton botonBuscar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jtResultado;
    private javax.swing.JTextField textRif;
    // End of variables declaration//GEN-END:variables

}
